import {Component, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../../core/net/fetch.service';
import {NzMessageService} from 'ng-zorro-antd';
import {GeneralSettings} from "../GeneralSettings";
import * as _ from 'lodash';
import {UtilService} from "../../../core/util/util.service";
import {RegionMngModel, SearchMaintainService} from "../search-maintain.service";

const coefficientArr = [0.50, 0.53, 0.50, 0.51, 0.54, 0.50, 0.51, 0.55, 0.53, 0.53, 0.50, 0.50, 0.53];
@Component({
    selector: 'app-mt-irrigated',
    templateUrl: './mt-irrigated.component.html',
    styleUrls: ['./mt-irrigated.component.scss', '../search-maintain.component.scss']
})
export class MtIrrigatedComponent implements OnInit {
    pageNum = 1;
    pageSize = 10;
    total: number;
    tableData = [];
    loading = true;
    searchForm: FormGroup;

    modalTitle: string = '';
    modalShow: boolean = false;
    detailForm: FormGroup;
    nzBodyStyle: any = {
        padding: '16px 20px 0'
    };

    props: any;
    irrigateNum: number;
    irrigateArea: number;
    canalLength: number;
    maxImport: number;
    generalChartOption = {
        color: ['#3398DB'],
        title: {
            text: '灌溉系数',
            fontSize: 16
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: [
                    '跃进渠管理处',
                    '西干渠管理处',
                    '红寺堡扬水管理处',
                    '秦汉渠管理处',
                    '盐环定扬水管理处',
                    '渠首管理处',
                    '汉延渠管理处',
                    '固海扬水管理处',
                    '唐徕渠管理处',
                    '中卫市水务局',
                    '七星渠管理处'
                ],
                axisLabel: {
                    interval: 0,
                    formatter: (value) => {
                        return value.split("").join("\n");
                    }
                    // rotate: 60
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                splitNumber: 5,
                min: (val) => {
                    return val.min - 0.02 > 0 ? val.min - 0.02 : 0;
                }
            }
        ],
        series: [
            {
                name: '灌溉系数',
                type: 'bar',
                label: {
                    show: true,
                    position: 'top'
                },
                // barWidth: '60%',
                data: [0.50, 0.53, 0.50, 0.51, 0.54, 0.50, 0.51, 0.55, 0.53, 0.53, 0.50, 0.50]
            }
        ]
    };
    statOpt: any = {};
    commonSelection: RegionMngModel;
    latestList: Array<any> = [];
    constructor(private fb: FormBuilder,
                private fetchService: FetchService,
                private message: NzMessageService,
                private util: UtilService,
                private searchService: SearchMaintainService,
                private params: GeneralSettings) {
        this.props = this.params;
    }

    ngOnInit() {
        // this.fetchService.post(`sys/sysDictValue/list`, {
        //     dictTypeId: '10002'
        // }).subscribe(resp => {
        //     console.log(resp);
        // });
        this.searchForm = this.fb.group({
            name: [],
            type: []
        });
        this.detailForm = this.fb.group({
            id: [''],
            name: ['', Validators.required],
            type: ['1', Validators.required],
            upperDistrictName: ['', Validators.required],
            cheadFlux: [''],
            trunkLegth: [''],
            irrigatedArea: [''],
            upperManageUnit: [''],
            headwaters: [''],
            county: ['', Validators.required],
            crop: ['']
        });
        this.latestList = this.searchService.getLatestList('mtIrr');
        this.searchService.regionMngDataChange.subscribe(data => {
            this.commonSelection = data;
            this.getGridData();
        });
    }
    getLatestData(data): void {
        this.searchForm.patchValue({
            name: data.keyword,
            type: null
        });
        this.getGridData(true);
    }
    openEditModal(item?): void {
        console.log(item);
        this.modalTitle = item ? `编辑${item.name}` : '新增灌区';
        item ? this.detailForm.patchValue(item) : this.detailForm.reset();
        this.modalShow = true;
    }

    onDelete(id) {
        this.fetchService.get(`wrs/wrsBdistrict/remove/${id}`).subscribe(resp => {
            this.message.info('删除成功');
            this.getGridData();
        });
    }

    onConfirm() {
        if (!this.detailForm.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        const data = this.detailForm.value;
        data.stationId = '1';
        if (data.id) {
            this.fetchService.post('wrs/wrsBdistrict/edit', data).subscribe(res => {
                this.message.success('修改成功');
                this.modalShow = false;
                this.getGridData();
            });
        } else {
            this.fetchService.post('wrs/wrsBdistrict/add', data).subscribe(res => {
                this.message.success('添加成功');
                this.modalShow = false;
                this.getGridData();
            });
        }
    }

    onCancel() {
        this.modalShow = false;
    }

    getGridData(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        const params = _.assign(_.cloneDeep(this.searchForm.value), this.commonSelection, {
            pageNum: this.pageNum,
            pageSize: this.pageSize
        });
        if (this.searchForm.value.name) {
            this.searchService.setLatestList('mtIrr', this.searchForm.value.name);
        }
        this.latestList = this.searchService.getLatestList('mtIrr');
        this.fetchService.post('wrs/wrsBdistrict/list', params).subscribe(res => {
            this.loading = false;
            if (res) {
                this.total = res['total'];
                this.tableData = res['list'];
            }
        });
        this.getRightPanelData();
    }

    getRightPanelData(): void {
        const params = _.assign(this.searchForm.value, this.commonSelection, {
            pageSize: 100000
        });
        this.fetchService.post('wrs/wrsBdistrict/list', params).subscribe(res => {
            if (res) {
                this.irrigateNum = res['total'];
                // this.irrigateArea = this.util.sum(this.util.getItemValues(
                //     res['list'],
                //     "irrigatedArea",
                //     true
                // ));
                // this.canalLength = this.util.sum(this.util.getItemValues(
                //     res['list'],
                //     "trunkLegth",
                //     true
                // ));
                // this.maxImport = this.util.max(this.util.getItemValues(
                //     res['list'],
                //     "maxWaterDiversionCapacity",
                //     true
                // ));
                const baseList = res["list"];
                baseList.forEach((item, index) => {
                    item['irrCoefficient'] = coefficientArr[index];
                });
                this.statOpt = {
                    statType: 'irrArea',
                    baseList
                };
            }
        });
    }
}
